//
//  Anktool.m
//  ainkjj
//
//  Created by zhiyiLiu on 2020/3/2.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Anktool.h"


#import <UMShare/UMShare.h>
#import <UShareUI/UShareUI.h>

@interface CALayer (Snap)

- (UIImage *)snapshotImage;

@end

@implementation CALayer (Snap)

- (UIImage *)snapshotImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self renderInContext:context];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

@implementation NSString (DKAdSetAdd)
- (BOOL)isNotBlank {
    NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    for (NSInteger i = 0; i < self.length; ++i) {
        unichar c = [self characterAtIndex:i];
        if (![blank characterIsMember:c]) {
            return YES;
        }
    }
    return NO;
}

@end

@implementation Anktool
+ (NSMutableAttributedString *)begin:(NSString *)begin begin_fontSize:(CGFloat)begin_fontSize begin_color:(UIColor *)begin_color cishu_num:(NSString *)cishu_num cishu_numFontSize:(CGFloat)cishu_numFontSize cishu_num_textColor:(UIColor *)cishu_num_textColor shegnjiang_img:(NSString *)shengjiang_img{
    
    
    // 创建一个富文本
    NSMutableAttributedString *beginAttStr = [[NSMutableAttributedString alloc] initWithString:begin];
    
    // 修改富文本中的不同文字的样式
    [beginAttStr addAttribute:NSForegroundColorAttributeName value:begin_color range:NSMakeRange(0, beginAttStr.length)];
    [beginAttStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:begin_fontSize] range:NSMakeRange(0, beginAttStr.length)];
    
    // 创建一个富文本
    NSMutableAttributedString *tipAttrStr = [[NSMutableAttributedString alloc] initWithString:@"次数 "];
    
    // 修改富文本中的不同文字的样式
    [tipAttrStr addAttribute:NSForegroundColorAttributeName value:rgb(153,153,153) range:NSMakeRange(0, tipAttrStr.length)];
    [tipAttrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, tipAttrStr.length)];
    
    
    // 创建一个富文本
    NSMutableAttributedString *cishu_numAttrStr = [[NSMutableAttributedString alloc] initWithString:cishu_num];
    
    // 修改富文本中的不同文字的样式
    [cishu_numAttrStr addAttribute:NSForegroundColorAttributeName value:cishu_num_textColor range:NSMakeRange(0, cishu_numAttrStr.length)];
    [cishu_numAttrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:cishu_numFontSize] range:NSMakeRange(0, cishu_numAttrStr.length)];
    
    
  
    
    
    NSMutableAttributedString *string = nil;
    string = [[NSMutableAttributedString alloc]initWithAttributedString:beginAttStr];
    [string appendAttributedString:tipAttrStr];
    [string appendAttributedString:cishu_numAttrStr];
    
    if (shengjiang_img.length > 0) {
        
        // 添加附件
        NSTextAttachment *imgAtt = [[NSTextAttachment alloc] init];
        // 图片
        imgAtt.image = [UIImage imageNamed:shengjiang_img];
        // 设置图片大小
        imgAtt.bounds = CGRectMake(2, 0, 7, 11);
        
        // 创建带有图片的富文本
        NSAttributedString *imgAttStr = [NSAttributedString attributedStringWithAttachment:imgAtt];
        [string appendAttributedString:imgAttStr];

    }
    
  
    return string;
    
}
+ (NSMutableAttributedString *)stringWithNum:(NSString *)numStr fontSize:(CGFloat)numFontSize color:(UIColor *)numColor text:(NSString *)text textFontSize:(CGFloat)textFontSize textColor:(UIColor *)textColor numFirst:(BOOL)flag{
    
    
    // 创建一个富文本
    NSMutableAttributedString *numAttrStr = [[NSMutableAttributedString alloc] initWithString:numStr];
    
    // 修改富文本中的不同文字的样式
    [numAttrStr addAttribute:NSForegroundColorAttributeName value:numColor == nil ? [UIColor redColor] : numColor range:NSMakeRange(0, numAttrStr.length)];
    [numAttrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:numFontSize] range:NSMakeRange(0, numAttrStr.length)];
    
    
    // 创建一个富文本
    NSMutableAttributedString *textAttrStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    // 修改富文本中的不同文字的样式
    [textAttrStr addAttribute:NSForegroundColorAttributeName value:textColor == nil ? [UIColor redColor] : textColor range:NSMakeRange(0, textAttrStr.length)];
    [textAttrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:textFontSize] range:NSMakeRange(0, textAttrStr.length)];
    
    
    NSMutableAttributedString *string = nil;
    if (flag == YES) {
        //        拼接
        string = [[NSMutableAttributedString alloc]initWithAttributedString:numAttrStr];
        [string appendAttributedString:textAttrStr];
    }else{
        string = [[NSMutableAttributedString alloc]initWithAttributedString:textAttrStr];
        [string appendAttributedString:numAttrStr];
        
    }
    
    
    return string;
    
}
+ (NSString *)strBlankHolder:(NSString *)string{
    if ([string isNotBlank]) {
        return string;
    }else{
        return @"";
    }
}

+ (BOOL)strIsBlank:(NSString *)string{
    return ![string isNotBlank];
}

+ (BOOL)is_num_alpha:(NSString *)string{
    NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
    s = [s invertedSet];
    NSRange r = [string rangeOfCharacterFromSet:s];
    if (r.location !=NSNotFound) {
        NSLog(@"the string contains illegal characters");
        return NO;
    }else{
        return YES;
    }
}
+(BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}

//作者：透支未来
//链接：https://www.jianshu.com/p/390280dbf90d
//来源：简书
//著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

+ (NSString *)wendu:(NSInteger)searchNum{
    searchNum = searchNum * 1000 / 1241;
    NSArray *numberArray = @[ @(2916), @(2910), @(2903), @(2896), @(2889), @(2882), @(2874), @(2865), @(2857), @(2848), @(2838), @(2828), @(2818), @(2807), @(2795), @(2783), @(2771), @(2758), @(2744), @(2730), @(2715), @(2700), @(2684), @(2668), @(2651), @(2633), @(2615), @(2596), @(2576), @(2556), @(2535), @(2514), @(2491), @(2469), @(2445), @(2421), @(2397), @(2371), @(2345), @(2319), @(2292)/*索引是40，代表0摄氏度*/, @(2264), @(2236), @(2208), @(2178), @(2149), @(2119), @(2088), @(2057), @(2026), @(1994), @(1962), @(1930), @(1897), @(1864), @(1831), @(1798), @(1765), @(1732), @(1698), @(1665), @(1631), @(1598), @(1565), @(1532), @(1500), @(1466), @(1434), @(1401), @(1369), @(1337), @(1306), @(1275), @(1244), @(1214), @(1184), @(1154), @(1125), @(1097), @(1069), @(1041), @(1014), @(987), @(961), @(935), @(910), @(885), @(861), @(838), @(815), @(792), @(770), @(749), @(728), @(707), @(687), @(668), @(649), @(631), @(613), @(595), @(578), @(562), @(545), @(530), @(515), @(500), @(486), @(472), @(458), @(445), @(432), @(420), @(408), @(396), @(385), @(374), @(363), @(353), @(343), @(333), @(324), @(314), @(306), @(297), @(289), @(281), @(273), @(265), @(258), @(250), @(244), @(237), @(230), @(224), @(218), @(212), @(206), @(201), @(195)];
    
    NSInteger cha = 9999;
    NSNumber *chaNum = @(9999);
    NSInteger chaIndex = 0;
    for (NSInteger i = 0; i < numberArray.count; i++) {
        NSNumber *n = numberArray[i];
        NSInteger tempCha = ABS(n.integerValue - searchNum);
        if (tempCha < cha) {
            cha = tempCha;
            chaNum = n;
            chaIndex = i;
        }
    }
    
//    NSLog(@"总数%lu 最接近:%@ 最小差是：%lu 索引是:%lu", (unsigned long)numberArray.count, chaNum, cha ,chaIndex);
    if (chaIndex == 40) {
        return @"0℃";
    }else if(chaIndex < 40){
        return [NSString stringWithFormat:@"-%lu℃", 40 - chaIndex];
    }else if(chaIndex > 40){
        return [NSString stringWithFormat:@"%lu℃", chaIndex - 40];
    }else{
        return @"----";
    }
}

//将十进制转化为十六进制
+ (NSString *)DecimalToHex:(int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:
                nLetterValue = [NSString stringWithFormat:@"%u",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
    }
    if(str.length == 1){
        return [NSString stringWithFormat:@"0%@",str];
    }else{
        return str;
    }
}
// 将NSData转换成十六进制的字符串
+ (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}
#pragma mark - ================== 渐变色 背景图  ==================

/// 生成一张指定 从颜色a到颜色b，线性渐变的图片

+ (UIImage *)gradient_img_create:(UIColor *)fromColor toColor:(UIColor *)toColor frame:(CGRect)frame{
    CAGradientLayer *gradientLayer = [self createGradientLayerWithFromColor:[fromColor colorWithAlphaComponent:1] toColor:[toColor colorWithAlphaComponent:1] frame:frame];
    UIImage *bgImg = [gradientLayer snapshotImage];
    return bgImg;
}
+ (CAGradientLayer *)createGradientLayerWithFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor frame:(CGRect)frame{
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)fromColor.CGColor,
                             (__bridge id)toColor.CGColor];
    gradientLayer.locations = @[@0.0, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 1.0);
    gradientLayer.endPoint = CGPointMake(1.0, 0);
    gradientLayer.frame = frame;
    return gradientLayer;
}
static UILabel *label;

+ (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font text:(NSString *)text numberOfLines:(NSInteger)lines{
    if (!label) {
        label = [UILabel new];
        label.numberOfLines = lines;
    }
    
    label.font = font;
    label.text = text;
    CGSize retSize = [label sizeThatFits:size];
    return retSize;
}

//作者：iOS_愛OS
//链接：http://www.jianshu.com/p/8c18c0c06e1a
//來源：简书
//著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

/**
 *  获取当前的屏幕展示的控制器
 *
 *  @return 控制器
 */

+ (UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    id  nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //    如果是present上来的appRootVC.presentedViewController 不为nil
    if (appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    }else{
        UIView *frontView = [[window subviews] objectAtIndex:0];
        nextResponder = [frontView nextResponder];
        //  这方法下面有详解
    }
    
    if ([nextResponder isKindOfClass:[UITabBarController class]]){
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    }else if ([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    }else{
        result = nextResponder;
    }
    DLog(@"------当前展示的控制器------%@",result);
    return result;
}

//获取视图的控制器
+ (UIViewController*)viewControllerForView:(UIView *)view {
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}


#pragma mark - ==================  分享 ==================
+ (void)fenxiangTopic:(NSInteger)topicId name:(NSString *)name desc:(NSString *)desc currentView:(UIView *)view {
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    [dict setObject:@(topicId).stringValue forKey:@"topicId"];
    
    //sender.userInteractionEnabled = NO;
    __block QMUITips *qmui_tip = [QMUITips showLoading:@"请求中..." inView:[Anktool viewControllerForView:view].view];
    
    [PPHTTPRequest req:@"java/app/topic/transmit" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            
            [qmui_tip showSucceed:@"分享中" hideAfterDelay:1];
            
            NSString *s = response[@"data"] ;
            if (s.length > 0) {
                
                //显示分享面板
                [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
                //                [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession)]];
                
                [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
                    // 根据获取的platformType确定所选平台进行下一步操作
                    [self shareWebPageToPlatformType:platformType image:[UIImage imageNamed:@"logo_share"] webpageUrl:s name:name desc:desc currentView:view];
                    
                }];
            }
            
        }
        else{
            
            
            [qmui_tip showError:response[@"error_msg"] hideAfterDelay:2];
            
        }
        
    } failure:^(NSError *error) {
        [qmui_tip showError:[error localizedDescription] hideAfterDelay:2];
        
    }];
}


+ (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType image:(UIImage *)image webpageUrl:(NSString *)webpageUrl name:(NSString *)name  desc:(NSString *)desc currentView:(UIView *)view
{
    
    
    NSString *title = @"";
    
    title = [NSString stringWithFormat:@"%@", name];
    desc = desc;
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    UMShareWebpageObject*shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:desc thumImage:image];
    
    //设置网页地址
    
    shareObject.webpageUrl =  webpageUrl;
    
    
    //分享消息对象设置分享内容对象
    
    messageObject.shareObject= shareObject;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:[Anktool viewControllerForView:view] completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            DLog(@"分享失败1");
//            [QMUITips showError:@"分享失败"];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
                [QMUITips showSucceed:@"分享成功"];
                DLog(@"分享成功");
            }else{
                UMSocialLogInfo(@"response data is %@",data);
//                [QMUITips showError:@"分享失败"];
                
                DLog(@"分享失败2");
            }
        }
    }];
}
@end

